package com.shareyi.simpleserver.core;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.OutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

public class PrintWriterResponseData implements ResponseData {
    PrintWriter writer;
    StringWriter backEnd;
    private boolean locked=false;
    private byte[] bytes=null;
    
    public PrintWriterResponseData() {
        backEnd = new StringWriter();
        writer = new PrintWriter( backEnd );
    }

    public long getLength() {
        writer.flush();
        if(locked)
           throw new RuntimeException("无法再次获取长度");
        try {
			bytes=backEnd.toString().getBytes("utf-8");
		} catch (UnsupportedEncodingException e) {
		}
        locked=true;
        return bytes.length;
    }

    public PrintWriter getPrintWriter() {
        return writer;
    }

    public void send(OutputStream os) throws IOException {
    	if(!locked)
    	{
        writer.flush();
        os.write( backEnd.toString().getBytes() );
    	}else os.write(bytes);
    }
}
